package personal.han.utils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author tanghan
 * @Description TODO
 * @date 2021/05/11/ 10:30:00
 */
public class JdbcUtils {

    public static Connection getConnection(String url, String username, String password) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        return DriverManager.getConnection(url, username, password);
    }

    public static void close(Connection connection,ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        String url = "jdbc:mysql://192.168.20.24/pcgl?useSSL=false&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull";
        String username = "root";
        String password = "123456";

        try {
            Connection connection = getConnection(url, username, password);
            String types[] = {"TABLE"};
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet tables = metaData.getTables("pcgl", null, "%file%", types);
            List<String> tableNames = new ArrayList<>();
            while (tables.next()){
                tableNames.add(tables.getString("TABLE_CAT")+"."+tables.getString("TABLE_NAME"));
            }
            System.out.println(tableNames);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
